<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>WebRTC 视频聊天</title>
    <style>
        #localVideo, #remoteVideo {
            width: 400px;
            height: 300px;
            border: 1px solid gray;
        }
    </style>
</head>
<body>
    <h1>WebRTC 视频聊天</h1>
    <button onclick="createOffer()">创建 Offer</button>
    <video id="localVideo" autoplay muted></video>
    <video id="remoteVideo" autoplay></video>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.1.3/socket.io.js"></script>
    <script src="{{ static_url('js/adapter.min.js') }}"></script>
    <script>
        var socket = io.connect('http://localhost:8080/chatroom'); // 注意添加 http:// 前缀

        var localStream;
        var localPeerConnection;
        var remotePeerConnection;

        // 获取本地视频流
        navigator.mediaDevices.getUserMedia({ video: true, audio: true })
            .then(function (stream) {
                console.log('成功获取本地视频流');
                var localVideo = document.getElementById('localVideo');
                localVideo.srcObject = stream;
                localStream = stream;
            })
            .catch(function (error) {
                console.log('获取本地视频流失败：', error);
            });

        // 创建本地 Peer 连接
        function createLocalPeerConnection() {
            localPeerConnection = new RTCPeerConnection();

            // 添加本地视频流到 Peer 连接
            localPeerConnection.addStream(localStream);

            // 监听 ICE 候选者
            localPeerConnection.onicecandidate = function (event) {
                if (event.candidate) {
                    console.log('发送 ICE 候选者');
                    socket.emit('ice_candidate', event.candidate);
                }
            };

            // 监听远程视频流
            localPeerConnection.onaddstream = function (event) {
                console.log('收到远程视频流');
                var remoteVideo = document.getElementById('remoteVideo');
                remoteVideo.srcObject = event.stream;
            };
        }

        // 创建 Offer
        function createOffer() {
            createLocalPeerConnection();

            // 创建 Offer
            localPeerConnection.createOffer()
                .then(function (offer) {
                    console.log('创建 Offer 成功');
                    return localPeerConnection.setLocalDescription(offer);
                })
                .then(function () {
                    console.log('发送 Offer');
                    socket.emit('offer', localPeerConnection.localDescription);
                })
                .catch(function (error) {
                    console.log('创建 Offer 失败：', error);
                });
        }

        // 添加更多函数和事件处理程序...

    </script>
</body>
</html>
